package com.powerbank.user.controller;

import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import com.powerbank.user.dto.WalletRechargeDTO;
import com.powerbank.user.dto.WalletWithdrawDTO;
import com.powerbank.user.service.WalletService;
import com.powerbank.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;

/**
 * 钱包控制器
 */
@Slf4j
@RestController
@RequestMapping("/wallet")
public class WalletController {

    @Autowired
    private WalletService walletService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取用户钱包信息
     */
    @GetMapping("/info")
    public Result<WalletInfoVO> getUserWallet(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            WalletInfoVO walletInfo = walletService.getUserWallet(userId);
            return Result.success("钱包信息获取成功", walletInfo);
        } catch (Exception e) {
            log.error("获取钱包信息失败：{}", e.getMessage(), e);
            return Result.error("获取钱包信息失败：" + e.getMessage());
        }
    }

    /**
     * 创建钱包充值订单
     */
    @PostMapping("/recharge")
    public Result<PaymentResultVO> createRechargeOrder(@RequestBody @Valid WalletRechargeDTO rechargeDTO,
                                                       HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        // 设置客户端IP
        rechargeDTO.setClientIp(getClientIpAddress(request));
        
        try {
            PaymentResultVO result = walletService.createRechargeOrder(userId, rechargeDTO);
            return Result.success("充值订单创建成功", result);
        } catch (Exception e) {
            log.error("创建充值订单失败：{}", e.getMessage(), e);
            return Result.error("创建充值订单失败：" + e.getMessage());
        }
    }

    /**
     * 申请提现
     */
    @PostMapping("/withdraw")
    public Result<WalletWithdrawResultVO> applyWithdraw(@RequestBody @Valid WalletWithdrawDTO withdrawDTO,
                                                        HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            WalletWithdrawResultVO result = walletService.applyWithdraw(userId, withdrawDTO);
            return Result.success("提现申请成功", result);
        } catch (Exception e) {
            log.error("申请提现失败：{}", e.getMessage(), e);
            return Result.error("申请提现失败：" + e.getMessage());
        }
    }

    /**
     * 设置支付密码
     */
    @PostMapping("/set-pay-password")
    public Result<Void> setPayPassword(@RequestParam @NotBlank(message = "支付密码不能为空") String payPassword,
                                       HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            boolean success = walletService.setPayPassword(userId, payPassword);
            return success ? Result.success("支付密码设置成功", (Void) null) : Result.error("支付密码设置失败");
        } catch (Exception e) {
            log.error("设置支付密码失败：{}", e.getMessage(), e);
            return Result.error("设置支付密码失败：" + e.getMessage());
        }
    }

    /**
     * 修改支付密码
     */
    @PostMapping("/change-pay-password")
    public Result<Void> changePayPassword(@RequestParam @NotBlank(message = "原支付密码不能为空") String oldPayPassword,
                                          @RequestParam @NotBlank(message = "新支付密码不能为空") String newPayPassword,
                                          HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            boolean success = walletService.changePayPassword(userId, oldPayPassword, newPayPassword);
            return success ? Result.success("支付密码修改成功", (Void) null) : Result.error("支付密码修改失败");
        } catch (Exception e) {
            log.error("修改支付密码失败：{}", e.getMessage(), e);
            return Result.error("修改支付密码失败：" + e.getMessage());
        }
    }

    /**
     * 验证支付密码
     */
    @PostMapping("/verify-pay-password")
    public Result<Boolean> verifyPayPassword(@RequestParam @NotBlank(message = "支付密码不能为空") String payPassword,
                                             HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            boolean verified = walletService.verifyPayPassword(userId, payPassword);
            return Result.success("验证完成", verified);
        } catch (Exception e) {
            log.error("验证支付密码失败：{}", e.getMessage(), e);
            return Result.error("验证支付密码失败：" + e.getMessage());
        }
    }

    /**
     * 获取钱包交易记录
     */
    @GetMapping("/transactions")
    public Result<PageResult<WalletTransactionVO>> getWalletTransactions(@RequestParam(defaultValue = "1") int page,
                                                                          @RequestParam(defaultValue = "10") int size,
                                                                          HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            PageResult<WalletTransactionVO> result = walletService.getWalletTransactions(userId, page, size);
            return Result.success("交易记录查询成功", result);
        } catch (Exception e) {
            log.error("查询交易记录失败：{}", e.getMessage(), e);
            return Result.error("查询交易记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取钱包统计信息
     */
    @GetMapping("/summary")
    public Result<WalletSummaryVO> getWalletSummary(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            WalletSummaryVO result = walletService.getWalletSummary(userId);
            return Result.success("钱包统计信息获取成功", result);
        } catch (Exception e) {
            log.error("获取钱包统计信息失败：{}", e.getMessage(), e);
            return Result.error("获取钱包统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 充值成功回调处理（内部接口）
     */
    @PostMapping("/recharge-callback/{paymentNo}")
    public Result<Void> processRechargeCallback(@PathVariable @NotBlank(message = "支付流水号不能为空") String paymentNo) {
        try {
            boolean success = walletService.processRechargeSuccess(paymentNo);
            return success ? Result.success("充值回调处理成功", (Void) null) : Result.error("充值回调处理失败");
        } catch (Exception e) {
            log.error("处理充值回调失败：{}", e.getMessage(), e);
            return Result.error("处理充值回调失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("Token不能为空");
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}